<template>
  <el-dialog
    width="1200px"
    :title="$t('m.sigin.sigin')"
    :visible.sync="popupVisible"
    :before-close="close"
    :close-on-click-modal="false"
    v-loading="dialogLoading">
    <!-- 根据通知单号返显明细 start-->
    <el-form align="left" ref="form" :model="detail" label-width="120px">
      <el-row>
        <el-col :span="3">
          <template v-if="Object.keys(detail).length">
            <el-image :src="qualitypictures" fit="cover">
              <div slot="error" class="image-slot">
                <img src="@/assets/defalut.png" alt />
              </div>
            </el-image>
          </template>
          <template v-else>
            <img src="@/assets/defalut.png" />
          </template>
        </el-col>
        <el-col :span="21">
          <el-row>
            <el-col :span="8">
              <el-form-item label="sku">
                <el-input maxlength="20" show-word-limit v-model="detail.productspeccode" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="supplierCode">
                <el-input maxlength="20" show-word-limit v-model="detail.suppliercode" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('m.in.productspec')">
                <el-input maxlength="20" show-word-limit v-model="detail.productspec" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('m.in.productname')">
                <el-input maxlength="20" show-word-limit v-model="detail.productname" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row type="flex" justify="end">
        <el-col :span="8" v-if="!completed">
          <el-form-item :label="$t('m.sigin.sigin')+$t('m.sigin.signquantity')">
            <el-input maxlength="20" v-model="detail.plannedquantity" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="!completed">
          <el-form-item :label="$t('m.quality.surplus')+$t('m.sigin.signquantity')">
            <el-input maxlength="20" v-model="amount" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="!completed">
          <el-form-item :label="$t('m.sigin.tsareacode')">
              <el-select
                v-model="tsareaid"
                filterable
                :label="$t('m.choose')+$t('m.sigin.tsareacode')">
                <el-option
                  v-for="(item,index) in tsareaData"
                  :key="index"
                  :label="item.code"
                  :value="item.id"
                  :disabled="item.selected"
                ></el-option>
              </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 根据通知单号查询明细 end-->

    <!-- table start -->
    <el-form ref="table" :model="tableDetail" label-width="80px" size="mini">
      <el-row>
        <el-col :span="24">
          <el-table
            ref="table"
            stripe
            empty-text
            fit
            tooltip-effect="dark"
            :data="tableDetail.tableData">
            <el-table-column align="center" type="index" :label="$t('m.index')" width="50"></el-table-column>
            <el-table-column align="center" :label="$t('m.sigin.signquantity')">
              <template slot-scope="scope">
                <el-input @input="validateNumber('signquantity',scope.$index)" maxlength="20" show-word-limit v-model.number="scope.row.signquantity" :disabled="completed||!scope.row.action"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('m.sigin.containertype')">
              <template slot-scope="scope">
                <el-input maxlength="20" show-word-limit v-model="scope.row.containertypename" disabled></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('m.page.container')+$t('m.code')">
              <template slot-scope="scope">
                <template v-if="completed||!scope.row.action">
                  <el-select v-model="scope.row.containercode" disabled></el-select>
                </template>
                <template v-else>
                  <el-select
                    v-model="scope.row.containerid"
                    filterable
                    :label="$t('m.choose')"
                    clearable
                    @change="(id)=>{triggerSelect(id,scope.$index,'containerData')}">
                    <el-option
                      v-for="(item,index) in containerData"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                      :disabled="item.selected"
                    ></el-option>
                  </el-select>
                </template>
              </template>
            </el-table-column>
            <template v-if="completed">
              <el-table-column align="center" :label="$t('m.sigin.tsareacode')" prop="tsareacode"></el-table-column>
            </template>
            <el-table-column align="center" :label="$t('m.strategy.batch')" width="300">
              <template slot-scope="scope">
                <el-form-item
                  v-for="(item,index) in scope.row.batchattr.filter((item)=>item.enable)"
                  :key="index"
                  :label="item.label"
                  :required="item.inputtype===1">
                  <!-- format:1.字符串输入框；2.数字输入框；3.日期选择；4.日期时间选择 -->
                  <template v-if="item.format===1">
                    <el-input
                      size="mini"
                      maxlength="20"
                      :disabled="completed||!scope.row.action||item.label==='入库日期'||item.inputtype===0"
                      v-model.trim="scope.row.batchattr[index].value"
                      @blur="inputTime(scope.$index,index)">
                    </el-input>
                  </template>
                  <template v-if="item.format===2">
                    <el-input
                      size="mini"
                      maxlength="20"
                      :disabled="completed||!scope.row.action||item.label==='入库日期'||item.inputtype===0"
                      v-model.number.trim="scope.row.batchattr[index].value"
                      @blur="inputTime(scope.$index,index)">
                    </el-input>
                  </template>
                  <template v-if="item.format===3">
                    <el-date-picker
                      size="mini"
                      v-model="scope.row.batchattr[index].value"
                      type="date"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :disabled="completed||!scope.row.action||item.label==='入库日期'||item.inputtype===0"
                      :placeholder="$t('m.in.choosedate')"
                      @change="pickTime(scope.$index,index)"
                    ></el-date-picker>
                  </template>
                  <template v-if="item.format===4">
                    <el-date-picker
                      size="mini"
                      v-model="scope.row.batchattr[index].value"
                      type="datetime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :disabled="completed||!scope.row.action||item.label==='入库日期'||item.inputtype===0"
                      :placeholder="$t('m.in.choosedate')"
                      @change="pickTime(scope.$index,index)">
                    </el-date-picker>
                  </template>
                </el-form-item>
                <el-form-item label="保质期" v-if="detail.expirationnum!==0&&isQualityPeriod">
                  <el-input v-model="detail.expirationnum" disabled>
                    <template slot="append">天</template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('m.sigin.locationcode')" width="180">
              <template slot-scope="scope">
                <el-input
                  :placeholder="$t('m.pleasechooselocaiton')"
                  v-model="scope.row.locationcode"
                  clearable
                  readonly
                  size="middle"
                  :disabled="completed||!scope.row.action"
                  @focus="showLocationList(scope.row.signquantity,scope.$index)"/>
              </template>
            </el-table-column>
              <el-table-column align="center" :label="$t('m.operation')">
                <template slot-scope="scope">
                  <template v-if="completed||!scope.row.action">
                    <el-button type="success" size="mini" @click="print([scope.row.qualitycontrolid])">{{$t('m.print')}}</el-button>
                  </template>
                  <template v-else>
                    <el-button type="primary" size="mini" @click="save(scope.row,scope.$index)">{{$t('m.save')}}</el-button>
                    <el-button v-if="tableDetail.tableData.length>1" type="danger" size="mini" @click="remove(scope.$index)">{{$t('m.delete')}}</el-button>
                  </template>
                </template>
              </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <!-- table end -->
    <el-row>
      <el-col :span="8" align="left" v-show="!completed">
        <el-button type="primary" @click="addContainer">{{$t('m.sigin.addSignDetail')}}</el-button>
      </el-col>
      <el-col :span="completed?24:16" :align="completed?'center':'right'">
        <el-button @click="close">{{completed?$t('m.close'):$t('m.sigin.quit')}}</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import common from '@/utils/common'
import { getLodop } from '@/utils/LodopFuncs'
import { timeFn } from '@/assets/mixins/rule/batchattr-validate'
export default {
  name:'signing-add-popup',
  props:['popupVisible', 'arrivalnoticeDetail','location'],
  data(){
    return {
      detail:{},
      filepath:window._config_.filepath, // 图片域名

      amount:0, // 理货数量
      tsareaid:'', // 暂存区id

      tableDetail:{
        tableData:[]
      },
      tableDataItem:{
        action:'add',
        signquantity:0, // 数量
        containerid:'', // 容器id
        containercode:'', // 容器号
        containertypeid:'', // 容器类型id
        containertypename:'', // 容器类型
        batchattr:[], // 批次属性
        locationcode:'', // 上架库位
        locationid:'' // 上架库位id
      },

      signindetailitems:[], // 已理货数据

      containerData:[], // 初始化容器列表
      tsareaData:[], // 初始化暂存位置列表

      activeLocationIndex:0, // 当前操作上架库位的理货明细index

      dialogLoading:false
    }
  },
  mounted(){
    this.getData(this.initFn)
    // 如果是查看的情况下，没必要调这两个接口
    if (!this.completed){
      this.getTsarea()
      this.getContainer()
    }
  },
  computed:{
    qualitypictures(){
      if(!this.detail.qualitypictures.quantitypicture||this.detail.qualitypictures.quantitypicture==='[{}]') return ''
      else if(!JSON.parse(this.detail.qualitypictures.quantitypicture).length) return ''
      else return `${this.filepath}${JSON.parse(this.detail.qualitypictures.quantitypicture)[0]['FilePath']}`
    },
    // 满足已到货数量===计划到货数量 true : 查看 ; false : 理货
    completed(){
      if(this.arrivalnoticeDetail.completed) return true // 表格：到货通知单，已确认到货的单。不管理货数量多少，统一为完成状态。
      let totalSignquantity = 0
      for(let i=0;i<this.signindetailitems.length;i++){
        totalSignquantity += this.signindetailitems[i].signquantity
      }
      if(!('actualquantity1' in this.detail)){
        return false // 新单
      } else if(totalSignquantity<this.detail.plannedquantity){
        return false // 剩余理货数量 < 总理货数量
      }
      return true
    },
    // 根据暂存区id，返回暂存区名字
    tsareaname(){
      let result = this.tsareaData.find((item)=>item.id === this.tsareaid)
      return result?name:''
    },
    // 是否显示保质期
    isQualityPeriod(){
      if(!this.detail) return false
      let batchattr = JSON.parse(this.detail.batchattr)
      return batchattr.some((item)=>item.label === '到期日期')
    }
  },
  watch:{
    // 选择完库位后，把对应的库位信息反显到tableItem里
    location(){
      this.$set(this.tableDetail.tableData[this.activeLocationIndex],'locationcode',this.location.locationcode)
      this.$set(this.tableDetail.tableData[this.activeLocationIndex],'locationid',this.location.locationid)
    }
  },
  methods:{
    validateNumber(key,index){
      this.$set(this.tableDetail.tableData[index],key,this.tableDetail.tableData[index][key].toString().replace(/[^\d]/g,''))
    },
    close(){
      if(this.completed){
        this.$emit('callback')
        this.$emit('close')
      } else {
        this.$confirm(`${this.$t('m.sigin.closeTips',{amount:this.amount})}?`, this.$t('m.noticemessage'), {
          confirmButtonText:this.$t('m.confirm'),
          cancelButtonText:this.$t('m.cancel'),
          type:'warning'
        }).then(() => {
          this.$emit('callback')
          this.$emit('close')
        })
      }
    },
    // 根据理货单号&&sku获取理货明细
    getData(callback){
      let { noticenumber, sku } = this.arrivalnoticeDetail
      let options = {
        method:'get',
        url:`/arrivalnotice/getdetailfn`,
        params:{
          noticenumber,sku
        }
      }
      this.$axios(options).then(({ data }) => {
        this.detail = this.cloneObject(data.arrivalNoticeDetailOutput)
        this.signindetailitems = data.signindetailitems || []
        // 处理下质检图片字段的数据
        if(this.detail.qualitypictures === '[{}]') this.detail.qualitypictures = '[]'
        if(!this.completed){ // 理货
          data.signindetailitems.map((item)=>{
            if(item.dynamiccolumn&&item.dynamiccolumn!=='[{}]'){
              item.batchattr = JSON.parse(item.dynamiccolumn)
              delete item.dynamiccolumn
            }
            return item
          })
        } else { // 查看理货
          data.signindetailitems.map((item)=>{
            if(item.dynamiccolumn&&item.dynamiccolumn!=='[{}]'){
              item.batchattr = JSON.parse(item.dynamiccolumn)
              delete item.dynamiccolumn
            }
            return item
          })
        }
        callback && callback(this.cloneObject(data.signindetailitems))
      })
    },
    // 初始化获取数据时执行
    initFn(signindetailitems){
      this.tableDetail.tableData = signindetailitems

      if (this.completed){
        // 数量已达标
        this.amount = 0
      } else {
        // 数量未达标
        this.amount = this.detail.actualquantity1?this.detail.actualquantity1:this.detail.plannedquantity
        let batchattr = []
        if(this.detail.batchattr && this.detail.batchattr !== '[{}]') batchattr = JSON.parse(this.detail.batchattr)
        for(let i=0;i<batchattr.length;i++){
          if(batchattr[i].label === '入库日期') batchattr[i].value = `${common.timestampSimple(new Date())} 00:00:00`
        }
        this.tableDataItem.batchattr = this.cloneObject(batchattr)
        this.tableDetail.tableData.push(this.cloneObject(this.tableDataItem))

        this.$set(this.tableDetail.tableData[this.tableDetail.tableData.length-1],'signquantity',this.amount)
      }
    },
    // 单条数据理货成功后回调函数
    endFn(signindetailitems){
      this.amount = this.detail.actualquantity1?this.detail.actualquantity1:this.detail.plannedquantity
      let totalAmount = 0
      for(let i=0;i<signindetailitems.length;i++){
        totalAmount += signindetailitems[i].signquantity
      }
      if(totalAmount>=this.detail.plannedquantity){ // 如果已理货数量>=总理货数量，表格数据直接替换
        this.tableDetail.tableData = signindetailitems
      } else { // 表格内容合并当前已添加，但未保存的理货数据
        let arr = this.tableDetail.tableData.filter((item)=>item.action)
        this.tableDetail.tableData = [...signindetailitems,...arr]
      }
    },
    // 获取容器区列表
    getContainer(){
      let options = {
        method:'get',
        url:`/container/list`
      }
      this.$axios(options).then(({ data }) => {
        for (let i = 0; i < data.length; i++){
          let { containercode:code, containerid:id, containercode:name, containertype, containertypeid } = data[i]
          this.containerData.push({code, id, name, containertype, containertypeid, selected:false})
        }
      })
    },
    // 获取暂存区列表
    getTsarea(){
      let options = {
        method:'get',
        url:`/tsarea/list`
      }
      this.$axios(options).then(({ data }) => {
        for (let i = 0; i < data.length; i++){
          if(data[i].type===1){
            let { tsareacode:code, tsareaid:id, tsareaname:name } = data[i]
            this.tsareaData.push({code, id, name})
          }
        }
      })
    },
    /*
      输入日期后触发的event ==> inputTime
      选择日期后触发的event ==> pickTime
      mixins file : batchattr-validate.js
    */
    ...timeFn,
    // 下拉框选中后触发的event
    triggerSelect(id, index, arrName){
      let containertype = '' // 容器类型
      let containertypeid = '' // 容器id
      if(id){
        let result = this.containerData.find((item)=>item.id === id)
        containertype = result.containertype
        containertypeid = result.containertypeid
      }

      this.$set(this.tableDetail.tableData[index],'containertypename',containertype)
      this.$set(this.tableDetail.tableData[index],'containertypeid',containertypeid)
      // 重置选中状态
      for (let i = 0; i < this[arrName].length; i++){
        this[arrName][i].selected = false
      }
      let name = arrName.slice(0, -4)
      // 根据tableData修改已被选中的状态
      for (let i = 0; i < this.tableDetail.tableData.length; i++){
        for (let j = 0; j < this[arrName].length; j++){
          if (this.tableDetail.tableData[i][name + 'id'] === this[arrName][j].id){
            this.tableDetail.tableData[i][name + 'code'] = this[arrName][j].code
            this[arrName][j].selected = true
            continue
          }
        }
      }
    },
    // 显示选择库位的dialog
    showLocationList(quantity,index){
      if(!quantity) return this.callbackMessage(this.$t('m.putInStorageQuantityNotNull'))
      let typelist = [1,2,3].join(',') // [1:收货区,2:存货区,3:拣货区,4:不良品区,5:退货区]
      this.activeLocationIndex = index
      let config = {
        params:{
          sku:this.detail.productspeccode,
          quantity,
          typelist
        }
      }
      let disabledLocation = []
      for(let i=0;i<this.tableDetail.tableData.length; i++){
        // 获取已经选择的库位id
        if(this.tableDetail.tableData[i].locationid) disabledLocation.push(this.tableDetail.tableData[i].locationid)
      }
      this.$emit('showLocationDialog',config,disabledLocation)
    },
    // 删除table选中项
    remove(index){
      if (this.tableDetail.tableData.length === 1) return
      this.$delete(this.tableDetail.tableData, index)
      // 重置选中状态
      for (let i = 0; i < this.containerData.length; i++){
        this.containerData[i].selected = false
      }
      // 根据tableData修改已被选中的状态
      for (let i = 0; i < this.tableDetail.tableData.length; i++){
        for (let j = 0; j < this.containerData.length; j++){
          if (this.tableDetail.tableData[i].containerid === this.containerData[j].id){
            this.containerData[j].selected = true
            continue
          }
        }
      }
    },
    // table增加一项
    addContainer(){
      let totalAmount = 0
      for (let i = 0; i < this.tableDetail.tableData.length; i++){
        if (this.tableDetail.tableData[i].signquantity <= 0)
          return this.callbackMessage(this.$t('m.enter')+this.$t('m.sigin.amount'))
        totalAmount += parseInt(this.tableDetail.tableData[i].signquantity)
      }
      if(totalAmount>=this.detail.plannedquantity)
        return this.callbackMessage(this.$t('m.sigin.overcount'))
      let item = this.cloneObject(this.tableDataItem)

      let hasAddItem = this.tableDetail.tableData.some((item)=>item.action)
      if(hasAddItem){ // 如果存在未保存的理货item
        let currentAmount = 0 // 已理货数量
        for (let i = 0; i < this.tableDetail.tableData.length; i++){
          currentAmount += parseInt(this.tableDetail.tableData[i].signquantity)
        }
        // 【数量】优化计算
        let surplus = this.detail.plannedquantity - currentAmount
        let prev = this.tableDetail.tableData[this.tableDetail.tableData.length - 1].signquantity
        item.signquantity = surplus >= prev ? (prev === 0 ? surplus : prev) : surplus
      } else {
        item.signquantity = this.detail.actualquantity1 || this.detail.plannedquantity
      }

      this.tableDetail.tableData.push(item)
    },
    save(row,index){
      // 1.判断是否漏选了暂存位置
      if(!this.tsareaid) return this.callbackMessage(this.$t('m.sigin.checktemporary'))
      // 2.验证tableData中signquantity的数量
      if(isNaN(row.signquantity)||!row.signquantity) return this.callbackMessage(this.$t('m.sigin.checkSignquantity1'))
      if(row.signquantity>this.amount) return this.callbackMessage(`${this.$t('m.sigin.checkSignquantity2')}${this.amount}`)
      // 3.验证batchattr
      for(let i=0;i<row.batchattr.length;i++){
        if(row.batchattr[i].inputtype===1&&!row.batchattr[i].value)
          return this.callbackMessage(`${row.batchattr[i].label}${this.$t('m.strategy.inputtype1')}`)
      }
      // 4.判断是否已经选择上架库位
      if(!row.locationid) return this.callbackMessage(`${this.$t('m.choose')}${this.$t('m.sigin.locationcode')}`)

      // 所有验证通过，处理下批次属性字段的格式
      let data = this.cloneObject(row)
      data.dynamiccolumn = JSON.stringify(data.batchattr)
      delete data.batchattr
      delete data.action
      let { noticenumber, sku } = this.arrivalnoticeDetail
      let {code:tsareacode} = this.tsareaData.find((item)=>item.id === this.tsareaid)
      let options = {
        method:'put',
        url:`/signin/addsignindetailitem`,
        params:{
          noticenumber,
          sku,
          tsareacode,
          tsareaid:this.tsareaid,
          limitationofreceipt:this.detail.limitationofreceipt
        },
        data
      }
      this.dialogLoading = true
      this.$axios(options).then(({ data,message }) => {
        // 成功后回调上个弹窗的接口，返回已到货数量
        this.callbackMessage(message,'success',1500,()=>{
          this.dialogLoading = false
          // this.tsareaid = '' // 重置暂存区
          this.tableDetail.tableData.splice(index,1)
          this.getData(this.endFn)
          // 触发打印模板
          this.print([data.qualitycontrolid])
        })
      }).catch(()=>{
        this.dialogLoading = false
      })
    },
    print(ids){
      let LODOP = getLodop()
      let that = this
      let options = {templateName:'quality'}
      that
        .$axios({
          method:'post',
          url:'/printtemplate/query',
          data:Object.assign(options,{ids})
        })
        .then(({data})=> {
          that.printContent = data
          eval(that.printContent)
          LODOP.SET_PRINT_PAGESIZE(1, '50mm', '30mm', '')
          LODOP.PREVIEW()
        })
    },
    formatTodayTimestamp(timestamp){
      let year = timestamp.getFullYear()
      let month = timestamp.getMonth() + 1
      if (month < 10) month = '0' + month
      let day = timestamp.getDate()
      if (day < 10) day = '0' + day
      return `${year}-${month}-${day}`
    }
  }
}
</script>
<style lang="scss" scoped>
.remove-icon {
  font-size: 30px;
  color: red;
  cursor: pointer;
}
.el-select{width: 100%;}
.batchattr-list{
  .list-item{
    margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;
    &:last-child{margin-bottom: 0;}
    .list-label{font-size: 12px;}
    .list-value{width: 200px;}
  }
}
.el-image{
  width: 124px; height: 124px;
  & ::v-deep .image-slot{display: flex; justify-content: center; align-items: center; background-color: #f5f7fa; width: 100%; height: 100%;}
}
.el-picker-panel ::v-deep .el-button{white-space: initial;}
.image-slot img{width: 100%; height: 100%;}
</style>